<template>
  <view
    class="from-select-address custom-comp"
    :class="[getDisabled && 'is-disabled', getBorder && 'is-border']"
    @click="chooseLocation"
  >
    <PickerValue
      v-if="!getDisabled || getVal"
      :placeholder="getPlaceholder"
      :value-text="getVal"
      :disabled="getDisabled"
      style="flex: 1"
      :icon-style="
        getVal && !getDisabled
          ? {
              color: 'rgb(192, 196, 204)',
              fontSize: '40rpx',
            }
          : {
              fontSize: '30rpx',
            }
      "
      :icon="getVal && !getDisabled ? '\ue724' : '\ue600'"
      @icon-click="handleClear"
    />
  </view>
</template>

<script setup lang="ts">
  import { useLocation } from '@/hooks/core/useLocation';
  import { isNullOrUnDef } from '@/utils/is';
  import { propTypes } from '@/utils/propTypes';
  import { computed } from 'vue';
  import { useFormItem } from '../hooks/useContext';
  import PickerValue from './PickerValue.vue';
  import { isArray } from 'lodash-es';

  const props = defineProps({
    modelValue: propTypes.string.def(''),
    placeholder: propTypes.string.def('请选择地址'),
    isBorder: propTypes.bool.def(true),
    disabled: propTypes.bool.def(false),
  });

  const emit = defineEmits(['update:modelValue', 'change']);
  const { getProps, setFormModel, formProps } = useFormItem({});
  const { parseAddress, chooseLocation: useChooseLocation } = useLocation();

  const getBorder = computed(() =>
    isNullOrUnDef(formProps?.border) ? props.isBorder : !formProps?.border,
  );

  const getVal = computed(() => {
    const val = (getProps.value.modelValue || props.modelValue) as string;
    if (!val || val === '[]' || (isArray(val) && val.length === 0)) return '';
    return parseAddress(val).address;
  });

  const getDisabled = computed(() => {
    return getProps.value.disabled || props.disabled;
  });

  const getPlaceholder = computed(() => {
    return getProps.value.placeholder || props.placeholder;
  });

  function chooseLocation() {
    if (getDisabled.value) return;
    const val = (getProps.value.modelValue || props.modelValue) as string;
    useChooseLocation(val, (address) => {
      setFormModel(address);
      emit('change', address);
      emit('update:modelValue', address);
    });
  }

  function handleClear() {
    if (getVal.value && !getDisabled.value) {
      emit('update:modelValue', '');
      emit('change', '');
      setFormModel([]);
    }
  }
</script>

<style lang="scss" scoped>
  @import '../styles/form.scss';
</style>
